const cluster = require('cluster');
const gitServer = require('./git-server/index.js');

function addWorker(gitRepoPath) {
  const worker = cluster.fork();
  worker.send({ repoPath: gitRepoPath });
  console.log('CLUSTER: Worker %d forked', worker.id);
  return worker;
}

if (cluster.isMaster) {
  const [gitRepoPath] = process.argv.splice(2);
  if (!gitRepoPath) {
    console.log('Miss parameter for git repo path');
    process.exit(1);
  }
  addWorker(gitRepoPath);
  cluster.on('exit', (worker, code, signal) => {
    console.log('CLUSTER: Worker %d died with exit code %d (%s)', worker.id, code, signal);
    setTimeout(() => {
      addWorker(gitRepoPath);
    }, 1000);
  });
} else {
  process.on('message', (({ repoPath }) => {
    const repos = gitServer(repoPath);
    // repos.on('push', (push) => {
    //   console.log(`push ${push.repo}/${push.commit} (${push.branch})`);
    //   push.accept();
    // });

    repos.on('fetch', (fetch) => {
      console.log(`fetch ${fetch.commit}`);
      fetch.accept();
    });

    const http = require('http');
    const server = http.createServer((req, res) => {
      repos.handle(req, res);
    });
    server.listen(process.env.PORT || 9526);
    server.on('listening', () => {
      const address = server.address();
      console.log(`Git server started on port ${address.port}`);
    });
  }));
}
